package com.client.rpcclient;


import com.client.util.SingletonFactory;
import com.client.util.UnProcessRequests;
import com.common.entity.RPCResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Zixiang Hu
 * @description 自定义客户端的处理逻辑
 * @create 2021-03-01-15:16
 */
@Slf4j
@AllArgsConstructor
@Builder
public class NettyClientHandler extends SimpleChannelInboundHandler<RPCResponse> {
    private static UnProcessRequests unProcessRequests = SingletonFactory.getObject(UnProcessRequests.class);

    // 对于客户端来说，读取到的信息是来自服务端的响应
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RPCResponse msg) throws Exception {
        unProcessRequests.completeRequest(msg);
        ReferenceCountUtil.release(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("NettyClientHandler发生异常，异常信息是{}", cause.getMessage());
        ctx.close();
    }

}
